<template>
  <view class="register-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>
    
    <!-- 注册内容 -->
    <view class="register-content">
      <!-- Logo和标题 -->
      <view class="header">
        <view class="logo">
          <uni-icons type="water" size="60" color="#ffffff"></uni-icons>
        </view>
        <text class="title">用户注册</text>
        <text class="subtitle">Create New Account</text>
      </view>
      
      <!-- 注册表单 -->
      <view class="register-form">
        <view class="form-item">
          <view class="input-wrapper">
            <uni-icons type="person" size="20" color="#2E7D32"></uni-icons>
            <input 
              v-model="registerForm.username" 
              placeholder="请输入用户名" 
              class="input-field"
              placeholder-style="color: #999"
              maxlength="20"
            />
          </view>
          <text v-if="usernameError" class="error-text">{{ usernameError }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <uni-icons type="locked" size="20" color="#2E7D32"></uni-icons>
            <input 
              v-model="registerForm.password" 
              placeholder="请输入密码" 
              :password="!showPassword"
              class="input-field"
              placeholder-style="color: #999"
              maxlength="20"
            />
            <uni-icons 
              :type="showPassword ? 'eye-slash' : 'eye'" 
              size="20" 
              color="#999" 
              @click="togglePassword"
            ></uni-icons>
          </view>
          <text v-if="passwordError" class="error-text">{{ passwordError }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <uni-icons type="locked" size="20" color="#2E7D32"></uni-icons>
            <input 
              v-model="registerForm.confirmPassword" 
              placeholder="请确认密码" 
              :password="!showConfirmPassword"
              class="input-field"
              placeholder-style="color: #999"
              maxlength="20"
            />
            <uni-icons 
              :type="showConfirmPassword ? 'eye-slash' : 'eye'" 
              size="20" 
              color="#999" 
              @click="toggleConfirmPassword"
            ></uni-icons>
          </view>
          <text v-if="confirmPasswordError" class="error-text">{{ confirmPasswordError }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <uni-icons type="email" size="20" color="#2E7D32"></uni-icons>
            <input 
              v-model="registerForm.email" 
              placeholder="请输入邮箱（可选）" 
              class="input-field"
              placeholder-style="color: #999"
              type="email"
            />
          </view>
          <text v-if="emailError" class="error-text">{{ emailError }}</text>
        </view>
        
        <view class="form-item">
          <view class="input-wrapper">
            <uni-icons type="phone" size="20" color="#2E7D32"></uni-icons>
            <input 
              v-model="registerForm.phone" 
              placeholder="请输入手机号（可选）" 
              class="input-field"
              placeholder-style="color: #999"
              type="number"
              maxlength="11"
            />
          </view>
          <text v-if="phoneError" class="error-text">{{ phoneError }}</text>
        </view>
        
        <view class="form-options">
          <view class="agreement" @click="toggleAgree">
            <view class="custom-checkbox" :class="{ 'checked': agreeTerms }">
              <uni-icons v-if="agreeTerms" type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @click.stop="showTerms">《用户协议》</text>
              和
              <text class="link" @click.stop="showPrivacy">《隐私政策》</text>
            </text>
          </view>
        </view>
        
        <button class="register-btn" @click="handleRegister" :disabled="isLoading || !agreeTerms">
          <uni-icons v-if="isLoading" type="spinner-cycle" size="20" color="#ffffff"></uni-icons>
          <text>{{ isLoading ? '注册中...' : '立即注册' }}</text>
        </button>
        
        <!-- 调试信息 -->
        <view class="debug-info" style="font-size: 20rpx; color: #999; margin-top: 20rpx; padding: 20rpx; background: #f5f5f5; border-radius: 10rpx;">
          <text style="display: block; margin-bottom: 10rpx;">调试信息：</text>
          <text style="display: block;">加载中: {{ isLoading }}</text>
          <text style="display: block;">同意条款: {{ agreeTerms }}</text>
          <text style="display: block;">按钮禁用: {{ isLoading || !agreeTerms }}</text>
          <text style="display: block;">用户名: {{ registerForm.username }}</text>
          <text style="display: block;">密码: {{ registerForm.password ? '已填写' : '未填写' }}</text>
        </view>
        
        <view class="login-link">
          <text>已有账号？</text>
          <text class="link" @click="goToLogin">立即登录</text>
        </view>
      </view>
    </view>
    
    <!-- 用户协议弹窗 -->
    <uni-popup ref="termsPopup" type="center" :mask-click="false">
      <view class="terms-popup">
        <view class="popup-header">
          <text class="popup-title">用户协议</text>
          <uni-icons type="close" size="24" color="#999" @click="closeTerms"></uni-icons>
        </view>
        <scroll-view scroll-y class="popup-content">
          <text class="terms-text">
            1. 用户在使用本系统前，请仔细阅读本协议。\n\n
            2. 用户注册成功后，将获得一个用户账号及相应的密码，该用户账号和密码由用户负责保管。\n\n
            3. 用户应当对以其用户账号进行的所有活动和事件负法律责任。\n\n
            4. 用户在使用本系统时，必须遵守中华人民共和国相关法律法规。\n\n
            5. 本系统有权在必要时修改本协议，修改后的协议将在本系统上公布。\n\n
            6. 如用户不同意修改后的协议，可以主动取消已获得的服务。\n\n
            7. 本协议的解释权归本系统所有。
          </text>
        </scroll-view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="closeTerms">我知道了</button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 隐私政策弹窗 -->
    <uni-popup ref="privacyPopup" type="center" :mask-click="false">
      <view class="privacy-popup">
        <view class="popup-header">
          <text class="popup-title">隐私政策</text>
          <uni-icons type="close" size="24" color="#999" @click="closePrivacy"></uni-icons>
        </view>
        <scroll-view scroll-y class="popup-content">
          <text class="privacy-text">
            1. 我们重视您的隐私保护。\n\n
            2. 我们收集的信息包括：用户名、密码、邮箱、手机号等。\n\n
            3. 我们使用这些信息来提供、维护和改进我们的服务。\n\n
            4. 我们不会向第三方出售、交易或转让您的个人信息。\n\n
            5. 我们采用适当的技术和组织措施来保护您的个人信息。\n\n
            6. 您有权访问、更正或删除您的个人信息。\n\n
            7. 如有任何疑问，请联系我们。
          </text>
        </scroll-view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="closePrivacy">我知道了</button>
        </view>
      </view>
    </uni-popup>
    
    <!-- 底部信息 -->
    <view class="footer">
      <text class="footer-text">© 2024 水质监测系统 版权所有</text>
      <text class="footer-text">技术支持：智能监测团队</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/user.js'

// 使用用户状态管理
const userStore = useUserStore()

// 响应式数据
const isLoading = ref(false)
const agreeTerms = ref(false)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
})

// 错误信息
const usernameError = ref('')
const passwordError = ref('')
const confirmPasswordError = ref('')
const emailError = ref('')
const phoneError = ref('')

// 弹窗引用
const termsPopup = ref(null)
const privacyPopup = ref(null)

// 切换密码显示
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

// 切换同意条款
const toggleAgree = () => {
  agreeTerms.value = !agreeTerms.value
  console.log('切换同意条款:', agreeTerms.value)
  uni.showToast({ 
    title: `同意条款: ${agreeTerms.value}`, 
    icon: 'none',
    duration: 1000
  })
}

// 表单验证
const validateForm = () => {
  let isValid = true
  
  // 清空错误信息
  usernameError.value = ''
  passwordError.value = ''
  confirmPasswordError.value = ''
  emailError.value = ''
  phoneError.value = ''
  
  // 验证用户名
  if (!registerForm.username.trim()) {
    usernameError.value = '请输入用户名'
    isValid = false
  } else if (registerForm.username.length < 3) {
    usernameError.value = '用户名至少3个字符'
    isValid = false
  } else if (!/^[a-zA-Z0-9_]+$/.test(registerForm.username)) {
    usernameError.value = '用户名只能包含字母、数字和下划线'
    isValid = false
  }
  
  // 验证密码
  if (!registerForm.password.trim()) {
    passwordError.value = '请输入密码'
    isValid = false
  } else if (registerForm.password.length < 6) {
    passwordError.value = '密码至少6个字符'
    isValid = false
  }
  
  // 验证确认密码
  if (!registerForm.confirmPassword.trim()) {
    confirmPasswordError.value = '请确认密码'
    isValid = false
  } else if (registerForm.password !== registerForm.confirmPassword) {
    confirmPasswordError.value = '两次密码输入不一致'
    isValid = false
  }
  
  // 验证邮箱（可选）
  if (registerForm.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(registerForm.email)) {
    emailError.value = '请输入正确的邮箱格式'
    isValid = false
  }
  
  // 验证手机号（可选）
  if (registerForm.phone && !/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    phoneError.value = '请输入正确的手机号格式'
    isValid = false
  }
  
  return isValid
}

// 处理注册
const handleRegister = async () => {
  console.log('点击注册按钮')
  console.log('表单数据:', registerForm)
  console.log('同意条款:', agreeTerms.value)
  
  if (!validateForm()) {
    console.log('表单验证失败')
    return
  }
  
  if (!agreeTerms.value) {
    uni.showToast({ title: '请先同意用户协议和隐私政策', icon: 'none' })
    return
  }
  
  console.log('开始注册...')
  isLoading.value = true
  
  try {
    const result = await userStore.register({
      username: registerForm.username,
      password: registerForm.password
    })
    
    if (result.success) {
      uni.showToast({ title: result.message, icon: 'success' })
      
      // 注册成功后跳转到登录页
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
    } else {
      uni.showToast({ title: result.message, icon: 'none' })
    }
    
  } catch (error) {
    console.error('注册错误:', error)
    uni.showToast({ title: '注册失败，请稍后重试', icon: 'error' })
  } finally {
    isLoading.value = false
  }
}

// 跳转到登录页
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/login/login'
  })
}

// 显示用户协议
const showTerms = () => {
  termsPopup.value.open()
}

// 关闭用户协议
const closeTerms = () => {
  termsPopup.value.close()
}

// 显示隐私政策
const showPrivacy = () => {
  privacyPopup.value.open()
}

// 关闭隐私政策
const closePrivacy = () => {
  privacyPopup.value.close()
}

</script>

<style lang="scss" scoped>
.register-container {
  height: 100vh;
  background: linear-gradient(135deg, #f8fffe 0%, #e8f5f0 100%);
  position: relative;
  overflow: hidden;
}

.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(46, 125, 50, 0.1);
  
  &.circle-1 {
    width: 200rpx;
    height: 200rpx;
    top: -100rpx;
    right: -100rpx;
  }
  
  &.circle-2 {
    width: 150rpx;
    height: 150rpx;
    bottom: 200rpx;
    left: -75rpx;
  }
  
  &.circle-3 {
    width: 100rpx;
    height: 100rpx;
    top: 300rpx;
    right: 50rpx;
  }
}

.register-content {
  position: relative;
  z-index: 1;
  padding: 80rpx 60rpx 60rpx;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  text-align: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 120rpx;
  height: 120rpx;
  background: linear-gradient(135deg, #2E7D32, #4CAF50);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 30rpx;
  box-shadow: 0 8rpx 32rpx rgba(46, 125, 50, 0.3);
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #2E7D32;
  margin-bottom: 10rpx;
  display: block;
}

.subtitle {
  font-size: 24rpx;
  color: #4CAF50;
}

.register-form {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  margin-bottom: 40rpx;
  backdrop-filter: blur(10px);
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 30rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 0 20rpx;
  height: 80rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s;
  
  &:focus-within {
    border-color: #2E7D32;
    background: #ffffff;
  }
}

.input-field {
  flex: 1;
  margin-left: 20rpx;
  font-size: 28rpx;
  color: #333;
}

.error-text {
  font-size: 22rpx;
  color: #e74c3c;
  margin-top: 10rpx;
  margin-left: 20rpx;
  display: block;
}

.form-options {
  margin-bottom: 40rpx;
}

.agreement {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.custom-checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
  transition: all 0.3s;
  
  &.checked {
    background: #2E7D32;
    border-color: #2E7D32;
  }
}

.agreement-text {
  font-size: 24rpx;
  color: #666;
  margin-left: 10rpx;
  line-height: 1.5;
  
  .link {
    color: #2E7D32;
    text-decoration: underline;
  }
}

.register-btn {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #2E7D32, #4CAF50);
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #ffffff;
  border: none;
  box-shadow: 0 4rpx 20rpx rgba(46, 125, 50, 0.3);
  margin-bottom: 30rpx;
  
  &:disabled {
    opacity: 0.6;
  }
}

.login-link {
  text-align: center;
  font-size: 24rpx;
  color: #666;
  
  .link {
    color: #2E7D32;
    margin-left: 10rpx;
  }
}

// 弹窗样式
.terms-popup, .privacy-popup {
  width: 600rpx;
  max-height: 80vh;
  background: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.popup-content {
  max-height: 500rpx;
  padding: 30rpx 40rpx;
}

.terms-text, .privacy-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
  white-space: pre-line;
}

.popup-footer {
  padding: 30rpx 40rpx;
  border-top: 1rpx solid #f0f0f0;
}

.confirm-btn {
  width: 100%;
  height: 70rpx;
  background: linear-gradient(135deg, #2E7D32, #4CAF50);
  color: #ffffff;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
}

.footer {
  text-align: center;
  margin-top: auto;
}

.footer-text {
  display: block;
  font-size: 20rpx;
  color: rgba(46, 125, 50, 0.6);
  margin-bottom: 10rpx;
}
</style>
